var baseUrl = './static/hyPhone/';
// var baseUrl = './';
require.config({
    baseUrl : baseUrl+"js",
    paths : {
        "jquery" : ["jquery"],
        "scrollbar" : ["scrollbar"],
        "phoPanel" : ["phoPanel"],
        "iconfont" : ["iconfont"],
        "phone" : ["phone"],
        "jquery-cookie":["jquery.cookie.min"]
    }
})
require(["jquery", "phone", "scrollbar", "phoPanel", "iconfont","jquery-cookie"],function($){
            var menusArr = [
                'btn_login',
                'btn_logout',
                'btn_ready',
                'btn_notready',
                'btn_answer',
                'btn_disconnect',
                'btn_callout',
                'btn_holdon',
                'btn_consult',
                'btn_transfer',
                'btn_callback',
                'btn_meet',
                'btn_monitor',
                'btn_insert',
                'btn_drop',
                'btn_reset',
                'btn_set',
                'btn_cooperation', // 坐席协作
                'btn_transferIvr', //转IVR
                'btn_assistService', //密语
                'btn_reconnectCall', //咨询接回
                'btn_singleStep' // 单步 转接、会议
            ]
            var oldState = {};
            var newState = {};
            var oldStateTxt = '置忙';
            var newStateTxt = '置忙';
            var curNotReadyTxt = '置忙';
            var timer = null, s = 0; // 计时显示
            var stateBgColors = [
                {state: '置忙',bgColor: '#dd3256'},
                {state: '置闲',bgColor: '#82be3f'},
                {state: '保持中',bgColor: '#d9a805'},
                {state: '通话中',bgColor: '#04c3e7'},
                {state: '振铃中',bgColor: '#d86109'},
                {state: '咨询中',bgColor: '#80c35a'},
                {state: '监听中',bgColor: '#4a85c8'},
                {state: '会议中',bgColor: '#5fc29b'}
            ];
            /*
           * 获取到states 变化量
           */
            var getNewStates = function(oldState, newState) {
                var obj = {};
                if (JSON.stringify(oldState) === "{}") {
                    console.log('get=state--0-', newState)
                    return newState
                } else {
                    console.log('get=state--1-', newState)
                    menusArr.forEach(function(item) {
                        if (item === 'btn_disconnect') {
                            obj[item] = newState[item]
                        } else if (oldState[item] !== newState[item]) {
                            obj[item] = newState[item]
                        }
                    })
                    return obj;
                }
            }

            /*
            * 获取到外显号并完成渲染
            */
            function explicitNumRender(data) {
                $('.callingNumberList').html('');
                if (data.Result === -1) return;
                data.split(',').forEach(function(e){
                    if(e != ''){
                        if(e.indexOf('tel:') == 0 || e.indexOf('sip:') == 0){
                            $('.callingNumberList').append('<li>' + e.substring(4) + '</li>');
                        }
                    }
                });
            }
            /*
            * 状态改变渲染函数
            */
            function updateStateRender(states, stateTxt, callBackData) {
                console.log('states:::::::::::::::')
                console.dir(stateTxt, states);
                // state 所有的值
                var $p = $('.phonebarstate>p'); // 置闲置忙显示
                var $ul = $('.phonebarstate>ul'); // 状态切换面板
                var $hold = $('.pho-state-change>.font1'); // 保持接回 显示
                var $consult = $('.pho-state-change>.font2'); // 咨询接回 显示
                var $answer = $(".phonebar>li:nth-child(1)"); // 接听 挂断 显示
                if(stateTxt) {
                    if(stateTxt !== '置忙') {  // 因为置忙全部换成小状态 了 stateTxt === '置忙': 代表置忙状态成立
                        $p.text(stateTxt);  // 有可能是 通话中、咨询中 等
                        // 置闲 第一个不显示
                        if (stateTxt === '置闲') {
                            $ul.find('li:first-child').hide();
                            $ul.find('li:not(:first-child)').show();
                            $('.phonebarstate').css('backgroundColor','#82be3f')
                        } else if (stateTxt === '整理') { // 整理 都显示
                            $ul.find('li').show();
                        } else {
                            $ul.find('li').hide();  // 其他 都不显示
                        }
                    } else {
                        if(stateTxt === '置忙'&&curNotReadyTxt=='置忙'){

                            $p.text(stateTxt);
                            $ul.find('li:first-child').show();
                            $ul.find('li:not(:first-child)').each(function() {
                                if ($(this).text() === stateTxt) {
                                    $(this).hide();
                                }else{
                                    $(this).show();
                                }
                            })
                        }else{

                            $p.text(curNotReadyTxt); // curNotReadyTxt 小状态接口中获取到的 小状态字段
                            $ul.find('li:first-child').show(); // 只显示第一个
                            // $ul.find('li:not(:first-child)').hide();
                            $ul.find('li:not(:first-child)').each(function() {
                                if ($(this).text() === curNotReadyTxt) {
                                    $(this).hide();
                                }
                            })
                        }

                        $('.phonebarstate').css('backgroundColor','#dd3256');
                    }
                    newStateTxt = stateTxt;
                    handleTiming(oldStateTxt, newStateTxt, callBackData);
                    oldStateTxt = stateTxt;
                    console.log('当前状态变化--web-', stateTxt)
                    if (stateTxt === '整理' || stateTxt === '置闲' || stateTxt === '置忙') {
                        $(".pho-state>ul>li:nth-child(1)").html('暂无通话')
                    }
                    if (stateTxt === '保持中') {
                        $answer.removeClass().addClass("iconfont icon-wutonghua");
                    }
                }
                var arr = Object.keys(states);
                arr.forEach(function(item,index) {
                    //注意保持和接回是同一个按钮 btn_holdon
                    var $item = $('.'+item);
                    if (states[item] === 1) { // calling
                        if (item === 'btn_holdon') {
                            $hold.text('保持');
                        } else if (item === 'btn_callback') {
                            $hold.text('接回');
                        }

                        if (item === 'btn_consult') {
                            $consult.text('咨询');
                        } else if (item === 'btn_reconnectCall') {
                            $consult.text('接回');
                        }

                        if ($item[0] && $item.attr('class').indexOf('calling') === -1) { // 如果没有calling
                            $item.addClass('calling')
                        }
                        // 登出 外呼 接听 挂断 振铃 单独处理
                        if(item === 'btn_answer') { // 可接听 显示振铃
                            $answer.removeClass().append('<img src="' + baseUrl + './images/calling.gif" style="width:30px;height:30px;border-radius:4px">');
                        } else if (item === 'btn_disconnect'){ // 可挂断 显示挂断
                            $answer.children().remove();
                            $answer.removeClass().addClass("iconfont icon-guaduan allowed");
                            // $answer.css('cursor','pointer');
                        } else if(item === 'btn_logout' || item === 'btn_ready'|| item === 'btn_notready') {
                            $answer.children().remove();
                            $answer.removeClass().addClass("iconfont icon-wutonghua");
                            $hold.text('保持');
                            $consult.text('咨询');
                        }else if(item === 'btn_logout') {
                            $answer.children().remove();
                            $answer.removeClass().addClass("iconfont icon-wutonghua");
                        }
                    } else {
                        console.log('值时0 的按钮')
                        if (item === 'btn_disconnect'){ // 显示不可挂断
                            if($answer[0] && $answer.attr('class').indexOf('icon-guaduan') !== -1) {
                                console.log('禁止点击挂断-', $answer, $consult.text());
                                $answer.removeClass('allowed').addClass('not-allowed'); // tyy-04-11修改
                                console.log('禁止点击设置完成-')
                            }
                        }
                        if((item !== 'btn_holdon' && item !== 'btn_callback') || (item === 'btn_holdon' && $hold.text() === '保持') || (item === 'btn_callback' && $hold.text() === '接回') ||
                            (item !== 'btn_consult' && item !== 'btn_reconnectCall') || (item === 'btn_consult' && $consult.text() === '咨询') || (item === 'btn_reconnectCall' && $consult.text() === '接回') ) {
                            if ($item[0] && $item.attr('class').indexOf('calling') !== -1) {
                                if(item === 'btn_reconnectCall' && $consult.text() === '咨询') {
                                    console.log('tyy0407 20:24去除接回事件的recall处理')
                                } else {
                                    $item.removeClass('calling');
                                    console.log('777778888888----', $item, item, $consult.text())
                                }
                            }
                        }
                    }
                })
            }
            /*
            * 计时器样式
            */
            function handleTiming(oldStateTxt, newStateTxt, callBackData) {
                var $span = $('.phonebarstate>span');
                var $phonebarstate = $('.phonebarstate');
                var $answer = $(".phonebar>li:nth-child(1)"); // 接听 挂断 显示
                if (oldStateTxt !== newStateTxt){
                    // 更新状态背景
                    var bgColorObj = stateBgColors.find(function(elem) {
                        return elem.state === newStateTxt
                    })
                    if(bgColorObj) {
                        $phonebarstate.css("background",bgColorObj['bgColor'])
                    } else {
                        $phonebarstate.css("background",'#e83333');
                    }
                    if(newStateTxt === '振铃中' || newStateTxt === '通话中' || newStateTxt === '咨询中' || newStateTxt === '保持中' || newStateTxt === '会议中'){

                        $answer.children().remove();
                        $answer.removeClass().addClass("iconfont icon-guaduan allowed");
                    }
                    if (newStateTxt === '振铃中' || newStateTxt === '通话中' || newStateTxt === '咨询中' || newStateTxt === '保持中' || newStateTxt === '会议中' || newStateTxt === '监听中') {



                        clearInterval(timer);
                        // 关掉旧计时
                        // 开启新计时
                        // 重新计时
                        var s;
                        // console.log('AgentStateTime' in callBackData);
                        // console.log(callBackData.hasOwnProperty('AgentStateTime'));
                        // console.log(callBackData['AgentStateTime']);
                        if (callBackData.hasOwnProperty('AgentStateTime')) {
                        //     // 时间转分秒数 2019/6/12 11:04:32
                            s = parseInt((new Date().getTime() - new Date(callBackData['AgentStateTime']).getTime())/1000);
                        } else {
                            s = 0;
                        }
                        timer = null;
                        timer = setInterval( function () {
                            s++;
                            var h = parseInt(s/3600);
                            h < 10&&(h="0"+h);
                            var m = parseInt(s%3600/60);
                            m < 10&&(m="0"+m);
                            var S = s%60;
                            s < 10&&(S ="0"+S);
                            $span.html('<span class="callcolor" style="color:white;"><b id="ptime">'+m+':'+S+'</b></span>');
                        }, 1000)
                    } else {
                        clearInterval(timer);
                        s = 0;
                        timer = null;
                        $span.html('--:--:--');
                    }
                }
            }

            /*
            * 登陆中渲染函数
            */
            function loginingRender() {
                // 登录进行中渲染
                $logining.show();
            }
            /*
            * 用户自定义 登陆之后渲染函数
            * res为1 则登录成功 res为0 则登录失败
            */
            function loginRender(res) {
                // 登录成功渲染
                if (res.Code === '0') {
                    oldState = {};
                    newState = {};
                    oldStateTxt = '置忙';
                    newStateTxt = '置忙';
                    curNotReadyTxt = '置忙';
                    timer = null, s = 0; // 计时显示
                    // 登录成功渲染
                    $logining.hide(1000);
                    $unknownTip.hide(500);
                    $phonebar.show(1000);
                    console.log('=========登录成功后')
                    window.webrtcPhoneIsLogin = true;
                    setTimeout(function() {
                      micCheck();
                    }, 3800)
                } else {
                    // 登陆失败渲染
                    $logining.hide(1000);
                    $loginfail.show(1000);
                    $unknownTip.show(500, function() {
                        $unknownTip.find('p').text(res.Msg);
                    });
                }
                // 获取智能助手配置----
                if (window.phoneUserInfo.channel && window.phoneUserInfo.channel === 'external') {
                    // 外部接入不显示智能助手
                    $('.autoAIResponse').css('display', 'none');
                } else {
                    // 内部接入显示智能助手
                    updateLoginAgentHelper();
                }
            }
            // 检测麦克风
            function micCheck() {
                navigator.mediaDevices.enumerateDevices().then(function(devices) {
                let audioinput = devices.filter(function(device) {return device.kind === 'audioinput' && device.deviceId});
                let audiooutput = devices.filter(function(device) {return device.kind === 'audiooutput' && device.deviceId});
                console.log(devices, '-----device******-----', audioinput, audiooutput);
                    if(audioinput && audioinput.length >0 && audiooutput && audioinput.length > 0) {
                        console.log('有音频的输入输出设备');
                    } else {
                        console.log('没有--音频的输入输出设备', $('.unknownTip').css('display'));
                        if (window.phoneUserInfo.TerminalType == '5') {
                            if($('.unknownTip').css('display') != 'block') {
                                $('.unknownTip').show(500, function() {
                                    let micErrorMsg = '获取音频设备权限失败，请检查您的麦克风与声音设备';
                                    $('.unknownTip').addClass('sipmlError');
                                    $('.unknownTip').find('p').text(micErrorMsg);
                                });
                            }
                        }
                    }
                })
            }
            function logoutRender() {

                oldState = {};
                newState = {};
                oldStateTxt = '置闲';
                newStateTxt = '置闲';
                curNotReadyTxt = '置闲';
                timer = null, s = 0; // 计时显示

                // 登出成功渲染
                console.log('0-=0-=0-=0=0=-0=0=0=0=0=');
                $('.pho-input').val('');
                $phonebar.hide(1000);
                $loginfail.hide(1000);
                window.webrtcPhoneIsLogin = false;
            }
            function smallStatusRender(arr) {
                // 小状态 显示
                if (typeof arr === 'object' && arr.length>0) {
                    var i = 0;
                    var leng = arr.length;
                    var tempHtmlArr = [];
                    $('#Statelist>li:not(:first-child)').remove();
                    $('#Statelist>li:first-child').after('<li data-type="self"><i class="iconfont icon-manglu"></i><a href="#">置忙</a></li>');
                    for(i; i < leng; i++) {
                        var liHtmlCode = '<li data-statusCode = '+arr[i].statusCode+'><i class="iconfont icon-xiaoxiu"></i><a href="">'+arr[i].statusName+'</a></li>';
                        tempHtmlArr.push(liHtmlCode);
                    }
                    $('#Statelist').append(tempHtmlArr.join(''));
                   // $('.phonebarstate').find('p').text(arr[0].statusName);
                    //curNotReadyTxt = arr[0].statusName;
                } else {
                    $('#Statelist>li:not(:first-child)').remove();
                    $('#Statelist>li:first-child').after('<li data-type="self"><i class="iconfont icon-manglu"></i><a href="#">置忙</a></li>');
                }
            }
            /*
            * 用户配置可使用菜单
            */
            var phone = new window.newPhone();
            phone.config.menus = menusArr.concat([]);
            /*
            * 用户传入渲染函数 顺序不能错
            */
            phone.defineRenderFn(loginingRender,loginRender,explicitNumRender,logoutRender, smallStatusRender);
            /*
            * 用户传入接收状态函数
            */
            phone.getStates(function(states, stateTxt, callBackData) {
                console.log('mainjs接收的state--', states, stateTxt)
                if (typeof states === 'object') {
                    //拿到值重新渲染menus; states 是 对象
                    newState = Object.assign({}, states);
                    var newStates = getNewStates(oldState, newState);
                    console.log('变化后state', stateTxt);
                    console.dir(newStates);
                    oldState = Object.assign({}, newState);
                    updateStateRender(newStates, stateTxt, callBackData); // 变化后的状态进行渲染
                } else if (states === 404){
                    $('.loginfail').text('电话因uc service停止服务被迁出，可尝试重新登录').show();
                } else if (states === -1) {
                    return;
                }
                if (callBackData) {
                    if(callBackData.EventType === 'AgentStatus_Unkown') {
                        $unknownTip.show(500, function() {
                            $unknownTip.find('p').text(callBackData.AgentMessage);
                        });
                    } else {
                        console.log('unknowTip--提示hide---', 6)
                        // console.log('$unknownTip', $unknownTip.text(), $unknownTip.attr('class'), $unknownTip.attr('class').indexOf('sipmlError'))
                        if($unknownTip.attr('class').indexOf('sipmlError') == -1) {
                            console.log('=================');
                            $unknownTip.hide(5000);
                        }
                    }
                    $('#textarea').html('');
                    $.each(callBackData,function(index, item) {
                        $('#textarea').append('<li><span>'+index+':</span>'+item+'</li>')
                    })
                }
            })
            /*
            * 用户传入弹屏处理函数
            */
            phone.getAlertScreenFn(function(data, state) {
                var showPhoneNum = '';
                if (state === 2) {  // 挂断
                    console.log('2挂断', state, data);
                    alertScreen(data, null, null, null);
                } else if (state === 0) { // 0是外呼
                    var ServiceDirect = 3;
                    showPhoneNum = data.DNIS.substring(4);
                    $(".pho-state>ul>li:nth-child(1)").text(data.DNIS.substring(4)) //呼入显示主叫
                    alertScreen(data, data.ANI.substring(4), data.DNIS.substring(4),ServiceDirect);
                } else {           // 1 是内呼
                    var ServiceDirect = 0;
                    showPhoneNum = data.ANI;
                    if (showPhoneNum.length === 11) {
                        showPhoneNum = showPhoneNum.slice(0, 3) + '****' + showPhoneNum.slice(7);
                    }
                    $(".pho-state>ul>li:nth-child(1)").text(showPhoneNum) // 呼出显示被叫
                    // alertScreen(data, data.DNIS, data.ANI, ServiceDirect);
                    alertScreen(data, data.DNIS, data.ANI, ServiceDirect);
                }
            })


            /*
            * 弹屏事件
            */
            function alertScreen(data, ANI, DNIS) {
                // ****  弹屏事件开始  *********
                // ****  弹屏事件开始  *********
                var tempObj = {
                    'SessionID': data.SessionID,
                    'ANI': ANI,
                    'DNIS': DNIS,
                    'EventType': data.EventType,
                    'CallType': data.CallType,
                    'IVRData': data.IVRData,
                    'ResSkill': data.ResSkill
                }
                // if (tempObj.CallType !== 'OUTBOUND') {
                //     var temp = tempObj.DNIS;
                //     tempObj.DNIS = tempObj.ANI;
                //     tempObj.ANI = temp;
                // }
                // $('.side_bar')[0].__vue__.$refs.callBar[0].$el.click();
                // getChildCallBarFun(tempObj);
                phoneUserInfo.alertScreen(tempObj);
                // ****  弹屏事件结束  *********
            }
            /*
            *
            */
            var userInfo = window.phoneUserInfo;
            phone.create();
            // 将phone 暴出
            window.phone = phone;
            /*
            * 用户进行事件绑定
            */

            $('.btn_login').click(function() {
                // 登录的时候传值放置
                // phone.loginConfig.password = $.md5(userInfo.password).toUpperCase();
                phone.loginConfig.password = userInfo.password;
                phone.loginConfig.agentID = userInfo.agentID;
                phone.loginConfig.entId = userInfo.entId;
                phone.loginConfig.sipUser = userInfo.sipUser;
                phone.loginConfig.TerminalType = userInfo.TerminalType;
                // phone.loginConfig.httpServerAddress = ucHttpServerAddress ? ucHttpServerAddress : userInfo.httpServerAddress;
                phone.defineEvent('btn_login');
            })

            $('.btn_logout').click(function() {
                phone.defineEvent('btn_logout');
            })
            /*
            * 加载css
            */
            var scriptarr = [
                '<link type="text/css" rel="stylesheet" href="' + baseUrl + './css/phonebar.css">'
            ];
            scriptarr = scriptarr.join('');
            $("head").append(scriptarr);
/*    '			<div class="form-control-feedback dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></div>',
        '			<ul class="dropdown-menu">',
        '				<li><a class="dest-type" data-type="1">分机</a></li>',
        '				<li><a class="dest-type" data-type="3">外线</a></li>',
        '				<li><a class="dest-type" data-type="2">工号</a></li>',
        '				<li><a class="dest-type" data-type="4">技能</a></li>',
        '			</ul>',
        '		</div>',
        '		<input type="text" class="form-control" id="txtDesc" maxlength="30">',*/
            /*
            * 加载DOM
            */
            var phoarray = [
                '<div class="alertInfo"><p></p><i class="iconfont icon-guanbi"></i></div>',
                '<div class="logining"><img src="' + baseUrl + './images/loading.gif">电话功能启动中，请稍后...</div>',
                '<div class="loginfail"><i class="iconfont icon-tanhao"></i>电话条登陆失败</div>',
                '<div class="unknownTip"><span>电话条错误提示</span><p>unknownTip</p><i class="iconfont icon-guanbi"></i></div>',
                '<ul class="phonebar">',
                '<li class="speak iconfont icon-wutonghua"></li>',
                '<li class="pho-state" style="margin-left:0px;">',
                '<ul style="width:110px;">',
                '<li style="padding-top:10px;text-align: center;">暂无通话</li>',
                '</ul>',
                '</li>',
                '<li class="phonebarstate">',
                '<p>置忙</p>',
                '<b class="iconfont icon-xiajiantou" id="Changestate" style="/* padding-left:4px; */color:white;"></b>',
                '<span>--:--:--</span>',
                '<ul class="pho-changeState-sub" id="Statelist">',
                '<li><i class="iconfont icon-zaixian"></i><a href="#">置闲</a></li>',
                '<li><i class="iconfont icon-manglu"></i><a href="#">置忙</a></li>',
                '</ul>',
                '</li>',
                '<li></li>',
                '<li class="pho-state-change btn_holdon btn_callback"><a href="#" class="font1 baochi">保持</a></li>',
                '<li class="pho-state-change btn_consult btn_reconnectCall">',
                '<a href="#" id="zixun" class="font2">咨询</a>',
                '<ul class="pho-advisory" id="zixunList" style="display:none" >',
                '<li class="pho-bohao-sub1"></li>',
                '<li class="pho-bohao-sub2 pho-advisory-sub2">',
                '<div class="pho-group-line">',
                '<span class="pho-group-line-btn">',
                '<span class="iconfont icon-weixuanzhong on"></span>',
                '<span class="pho-group-innerline">内线</span>',
                '</span>',
                '<span class="pho-group-line-btn pho-group-outerline">',
                '<span class="iconfont icon-weixuanzhong"></span>',
                '<span class="pho-group-innerline">外线</span>',
                '</span>',
                '</div>',
                '<ul class="pho-chioces1">',
                '<li class="pho-group">',
                '<div class="scrollbar-inner">',
                '<ul>',
                '<li class="searchStaff">',
                '<i class="iconfont icon-iconfonticonfontsousuo1"></i>',
                '<input maxlength="11" type="text" placeholder="搜索员工" class="pho-input searchInput">',
                '</li>',
                '</ul>',
                '</div>',
                '</li>',
                '</ul>',
                '<ul class="pho-chioces2">',
                '<!--选择外线时-->',
                '<li></li>',
                '</ul>',
                '</li>',
                '<li class="pho-group-confirm"><a>确定</a></li>',
                '<li class="pho-group-confirm-tran" style="display:none"><a>转接</a></li>',
                '<li class="pho-group-confirm-meet" style="display:none"><a>会议</a></li>',
                '</ul>',
                '</li>',
                '<li class="pho-state-change btn_transfer"><a href="#" class="font3">转接</a></li>',
                '<li class="pho-state-change btn_meet"><a href="#" class="font4">会议</a></li>',
                '<li class="pho-state-change btn_transferIvr" style="width: 45px;display: none;"><a href="#" class="font8">转IVR</a></li>',
                '<li class="pho-state-change btn_monitor"><a href="#" class="font5">监听</a></li>',
                '<li class="pho-state-change btn_drop"><a href="#" class="font6">强拆</a></li>',
                '<li class="pho-state-change btn_insert"><a href="#" class="font7">强插</a></li>',
                '<li class="pho-state-change btn_cooperation" style="display: none;"><a href="#" class="font9">协作</a></li>',
                '<li class="pho-state-change btn_assistService btn_assistServiceEnd" style="display: none;"><a href="#" class="font10">密语</a></li>',
                //'<li class="pho-state-change btn_singleStep"><a href="#" class="font11">单步</a></li>',
                '<li class="iconfont icon-chongzhi1 pho-chongzhi-li">',
                '<audio id="audio_remote" autoplay="autoplay"> </audio>',
                '<audio id="audio_local" autoplay="autoplay"> </audio>',
              '<ul class="pho-chongzhi">',
                '<li class="htn_reset">重置</li>',
                '<li class="setOnCall">设置</li>',
                '<li class="btn_transferIvr"><span style="border-radius: 0px;margin-left:-10px;" class="iconfont icon-weixuanzhongduoxuan"></span><span>转IVR</span></li>',
                '<li class="btn_cooperation"><span style="border-radius: 0px;margin-left:-10px;;" class="iconfont icon-weixuanzhongduoxuan"></span><span>协作</span></li>',
                '<li class="btn_assistService"><span style="border-radius: 0px;margin-left:-10px;" class="iconfont icon-weixuanzhongduoxuan"></span><span>密语</span></li>',
                '</ul>',
                '</li>',
                '<li style="position: absolute;right:0px;top:44px;" class="callSetting">',
                '<div class="setUp">',
                '<div class="setUpTitle">设置<i class="iconfont icon-guanbi"></i></div>',
                '<div class="setUpConfigure" style="position: relative;">',
                '<div class="automaticResponse">',
                '<span style="color:#4f5866;display:block;padding:10px 0px 10px 20px;">主叫号码</span>',
                '<span style="border-radius: 0px;margin-left:34px;margin-bottom:10px;" class="iconfont icon-weixuanzhongduoxuan"></span><span>启用主叫号码</span>',
                '</div>',
                '<div class="callingNumberBox">',
                '<input class="callingNumber" type="text" readonly="value"/>',
                '<ul class="callingNumberList">',
                '</ul>',
                '</div>',
                '<div class="autoSetReadyResponse">',
                '<span style="color:#4f5866;display:block;padding:10px 0px 10px 20px;">自动设置</span>',
                '<span style="border-radius: 0px;margin-left:34px;margin-bottom:10px;" class="iconfont icon-weixuanzhong" id="autoReady"></span><span>自动置闲</span>',
                '<span style="border-radius: 0px;margin-left:34px;margin-bottom:10px;" class="iconfont icon-weixuanzhong" id="autoNotReady"></span><span>自动置忙</span>',
                '<br/>',
                '<div class="autoSetAnswer">',
                '<span style="border-radius: 0px;margin-left:34px;margin-bottom:10px;" class="iconfont icon-weixuanzhongduoxuan" id="autoAnswerCallIn"></span><span>呼入自动接听</span>',
                '</div>',
                '<br/>',
                '<input class="acwTimer" id="acwTimer" type="number" placeholder="事后整理时长(秒)" min="0"/>',
                '</div>',
                '<div class="autoAIResponse">',
                '<span style="color:#4f5866;display:block;padding:10px 0px 10px 20px;">智能坐席助手</span>',
                '<span style="border-radius: 0px;margin-left:34px;margin-bottom:10px;" class="iconfont icon-weixuanzhongduoxuan"></span><span>启用智能坐席助手</span>',
                '</div>',
                '<button style="position: absolute;right: 60px;bottom: 10px;outline:none;background:#49CC81;width:40px;height:24px;border:none;border-radius:4px;color:white;font-size:12px;cursor: pointer;" class="Determine">确定</button>',
                '<button style="position: absolute;right: 10px;bottom: 10px;outline:none;background:#4f5866;width:40px;height:24px;border:none;border-radius:4px;color:white;font-size:12px;cursor: pointer;" class="Unset">取消</button>',
                '</div>',
                '</div>',
                '</li>'
            ];
            phoarray = phoarray.join('');
            // var statusphone =false
            if( window.phoneUserInfo.entId=="JSSJ"){
                // debugger
                    $("body").append(phoarray);
                    // window.phoneUserInfo.entId="JSSJ1"
                }
                
            // }
            
            /*
          * 初始化位置
          */
            var posiX = userInfo.positionX;
            var posiY = userInfo.positionY;
            $('.phonebar').css({'position': 'absolute','top': posiX + 'px','left': posiY + 'px'})
            $('.logining').css({'position': 'absolute','top': posiX + 'px','left': posiY + 'px'})
            $('.loginfail').css({'position': 'absolute','top': posiX + 'px','left': posiY + 'px'})
            $('.unknownTip').css({'position': 'absolute','right': 30 + 'px','top': posiX + 'px'})
            /*
            * 页面初始状态
             */
            var $alertInfo = $('.alertInfo');
            var $logining = $('.logining');
            var $loginfail = $('.loginfail');
            var $unknownTip = $('.unknownTip');
            var $phonebar = $('.phonebar');
            var $zixunList = $('#zixunList');
            var $statelist = $('.Statelist')
            var $advisoryHead = $zixunList.find('.pho-bohao-sub1') // 咨询面板头部
            var $settingPanel = $('.pho-chongzhi'); //设置重置面板
            var $callSetting = $('.callSetting')  //主叫号码面板
            var $callingNumberList = $('.callingNumberList'); //主叫号码列表
            var $callingNumber = $('.callingNumber'); //已选主叫号码
            $alertInfo.hide();
            $logining.hide();
            $loginfail.hide();
            $unknownTip.hide();
            $settingPanel.hide();
            $statelist.hide();
            $phonebar.hide();

            // 电话条全部隐藏
            function phoneAllHide() {
                console.log('*********************************************')
                console.log('调用了all隐藏')
                $alertInfo.hide();
                $logining.hide();
                $loginfail.hide();
                $unknownTip.hide();
                $settingPanel.hide();
                $statelist.hide();
                $phonebar.hide();
            }
            window.phoneAllHide = phoneAllHide

             //移出状态自动隐藏
           $("#Statelist").hover(function () {
                 $("#Statelist").show();
            },function () {//隐藏
                 $("#Statelist").hide();
            });

            /*
            * 初始化参数变量
             */
            var explicitNumGet = $.cookie('explicitNum');
            var explicitNum = '';  //外显号码
            if(null!=explicitNumGet && explicitNumGet!=''&& typeof(explicitNumGet)!='undefined'){
                explicitNum = explicitNumGet;
            }
            phone.config.explicitNum = explicitNum;
            var showType = ''; //0 咨询 2监听 3单步
            var showListType = ""; //0-咨询 1-转接 2-监听

            var targetNum,conferenceParty;




            var autoReadyKeyGet = $.cookie('autoReadyKey');

             var autoReadyVal = '';  //自动置忙
             if(null!=autoReadyKeyGet && autoReadyKeyGet!=''&& typeof(autoReadyKeyGet)!='undefined'){
                 autoReadyVal = autoReadyKeyGet;
             }
            phone.config.autoReadyKey = autoReadyVal;

            var acwTimerGet = $.cookie('acwTimerKey');

            var acwTimerVal = 0;  //自动示忙时长
            if(null!=acwTimerGet && acwTimerGet!=''&& typeof(acwTimerGet)!='undefined'){
                acwTimerVal = acwTimerGet;
            }

            phone.config.acwTimerKey = acwTimerVal;

            //默认不启动AI助手
             var autoAIHelpKeyGet  = $.cookie('autoAIHelpKey');
             var autoAIHelpVal = '';  //默认不启动AI助手
             if(null!=autoAIHelpKeyGet && autoAIHelpKeyGet!=''&& typeof(autoAIHelpKeyGet)!='undefined'){
                 autoAIHelpVal = autoAIHelpKeyGet;
             }
             phone.config.autoAIHelpKey = autoAIHelpVal;

            // 初始化设置中的呼入自动应答
            var autoAnswerCallInKeyGet  = $.cookie('autoAnswerCallInKey');
            var autoAnswerCallInVal = '';  //默认不启动AI助手
            if(null!=autoAnswerCallInKeyGet && autoAnswerCallInKeyGet!=''&& typeof(autoAnswerCallInKeyGet)!='undefined'){ // 自动应答
                autoAnswerCallInVal = autoAnswerCallInKeyGet;
            } else {

            }
            phone.config.autoAnswerCallInKey = autoAnswerCallInVal;
            console.log('初始化00000-----', phone.config)
            // ----------------------自动应答结束---------

            /**
             * 登录后获取初始智能助手
             */
            function updateLoginAgentHelper() {
                // 1.判断智能助手是否开启
                console.log('初始话-之恩呢助手-----');
                getAgentHelperAuth(function(res) {
                    console.log('外部获取智能助手', res, phone.config);
                    var autoAIHelpValLogin = '';
                    if(res && res.data) {
                        // 2.开启智能助手
                        setTimeout(function() {
                            let param = {state: 'ON'};
                            setAgentHelperAuth(param, function(data) {
                                console.log('外呼设置-开启智能助手-', data);
                                if (data.data && res.code == 200) {
                                    autoAIHelpValLogin = 'autoAIHelp';
                                } else {
                                    autoAIHelpValLogin = '';
                                }
                                phone.config.autoAIHelpKey = autoAIHelpValLogin;
                                $.cookie('autoAIHelpKey', phone.config.autoAIHelpKey, { expires: 365 });
                            });
                        }, 1000)
                    } else {
                        console.log('没开启过智能助手---')
                    }
                    phone.config.autoAIHelpKey = autoAIHelpValLogin;
                    $.cookie('autoAIHelpKey', phone.config.autoAIHelpKey, { expires: 365 });
                })
            }
            // 启动或关闭只能助手
            function setAgentHelperAuth(param, callBack) {
                param.agentDn = window.phoneUserInfo.sipUser;
                param.entId = window.phoneUserInfo.entId;
                param.jobNumber = window.phoneUserInfo.agentID;
                $.ajax({
                    url: '/aiat/oauth/v2/switch',
                    type: "POST",
                    data: param,
                    success: function(res) {
                        console.log('智能助手开关-结果--', res)
                        if(res && res.code == 200) {
                            if (callBack) {
                                callBack(res);
                            }
                            var toOutParam = {};
                            toOutParam.actionState = param.state;
                            toOutParam.data = res.data;
                            toOutParam.message = res.message;
                            console.log('智能助手启用/关闭操作-结果-', toOutParam, window.agentHelperReceiveMassage);
                            if(window.agentHelperReceiveMassage) {
                                window.agentHelperReceiveMassage(toOutParam)
                            } else {
                                setTimeout(function(){
                                    console.log('1s后再次--智能助手启用/关闭操作-结果-', toOutParam, window.agentHelperReceiveMassage)
                                    window.agentHelperReceiveMassage ? window.agentHelperReceiveMassage(toOutParam) : null;// 启动成功/关闭成功智能助手
                                }, 1000)
                            }
                            // window.agentHelperReceiveMassage ? window.agentHelperReceiveMassage(toOutParam) : null;// 启动成功/关闭成功智能助手
                        } else {
                            if (callBack) {
                                callBack(res);
                            }
                            $unknownTip.show(500, function() {
                                $unknownTip.find('p').text('智能助手操作失败，' + res.message);
                            });
                        }
                    }
                })
            }

            // 获取智能助手
            function getAgentHelperAuth(callBack) {
                console.log('获取只能助手--', callBack);
                let param = {};
                param.agentDn = window.phoneUserInfo.sipUser;
                param.entId = window.phoneUserInfo.entId;
                param.jobNumber = window.phoneUserInfo.agentID;
                $.ajax({
                    url: '/aiat/oauth/v2/find/switch/state',
                    type: "POST",
                    data: param,
                    success: function(res) {
                        if(res && res.code == 200 && callBack) {
                            callBack(res);
                        }
                    }
                })
            }

            /*
            * 将服务器收到的msg转为树形结构对象30006:业务咨询;:胡静::24|
            */
            function msg2Tree(msg){
                var emps=msg.split("|");
                console.log(emps)
                var hash={};
                for(var i=0;i<emps.length;i++){
                    var emp=emps[i];
                    var fields=emp.split(":");
                    if(fields.length > 1){
                        var groups=fields[1].slice(0,-1).split(";");
                        for(var j=0;j<groups.length;j++){
                            var gname=groups[j];
                            hash[gname]=(hash[gname]||[]).concat({eid:fields[0],ename:fields[2],endn:fields[5]});
                        }
                    }
                }
                return hash;
            }
            /*
            * 将树形结构对象生成ul下的多个li html片段
             */
            function tree2html(tree){
                var html="";
                for(var key in tree){
                    var li=[
                        '<li>',
                        '<b class="iconfont icon-xiajiantou" style="cursor:pointer;" data-group="xiajiantou"></b>',
                        '<span class="iconfont icon-weixuanzhong on" data-choice="xuanxiang" style="display:none"></span>',
                        '<span class="skillGroupName">'+key+'</span>',
                        '<ul data-group="phon-group">'
                    ];
                    var emps=tree[key];
                    for(var i=0;i<emps.length;i++){
                        var emp=emps[i];
                        console.log('-=========------', emp)
                        li=li.concat([
                            '<li>',
                            '<span class="iconfont icon-weixuanzhong"></span>',
                            // '<span style="margin-right:10px;">工号  <span></span></span>',
                            '<span>'+emp.ename+'(<span data-eid="eid">'+emp.eid+'</span>)<span data-edn="endn" style="display: none;">'+emp.endn+'</span></span>',
                            '</li>'
                        ])
                    }
                    li=li.concat([
                        '</ul>',
                        '</li>',
                    ]);
                    html+=li.join("");
                }
                return html;
            }

            //员工搜索
            $(".searchStaff>input:text").keyup(function(){
                console.log('输入内容', $(this).val())
                searchInTree($(this).val());
            })
            function searchInTree(kw){
                var parentUlSelector="#zixunList";
                kw=kw.replace(/^\s+|\s+$/g,"");
                console.log('kw=  ', kw)
                if(kw.length==0){
                    console.log('kw.length==0');
                $('.searchStaff').nextAll().find('[data-group=phon-group]').find('li').show();
                $('.searchStaff').nextAll().find('[data-group=phon-group]').find('li').css('display', 'block');
                console.log('ll2', $('.searchStaff').nextAll().find('[data-group=phon-group]'))
                }else{
                console.log('kw.length:', kw.length);
                var chooseKw = 'li:contains('+kw+')';
                var notChooseKw = 'li:not(:contains('+kw+'))'
                $('.searchStaff').nextAll().find('[data-group=phon-group]').find(chooseKw).css('display', 'block');
                $('.searchStaff').nextAll().find('[data-group=phon-group]').find(notChooseKw).css('display', 'none');
                }
            }

            /*
            * 按钮事件 显示置闲置忙面板
            * 切换置闲置忙状态
             */
            $phonebar.on('click', '.phonebarstate', function (e) {
                $("#Statelist.pho-changeState-sub").toggle();
            })
            $("#Statelist.pho-changeState-sub").on("click","li",function(e) {
                e.stopPropagation();
                e.preventDefault();
                var targetTxt = $(this).children("a").text();
                var curStatus = $('.phonebarstate>p').text();
                console.log("targetTxt="+targetTxt);
                console.log("curStatus="+curStatus);
                var that = this;
                if ($(this).data('type') === 'self'||targetTxt === '置忙') { // 点击是自己写入的置忙 ，非小状态
                    curNotReadyTxt = targetTxt;
                    phone.defineEvent('btn_notready');
                } else if(targetTxt === '置闲') { //点击是置闲
                    if (curStatus !== '置闲') {
                        phone.defineEvent('btn_ready');
                    }
                } else if (targetTxt !== '置闲'&&targetTxt !== '置忙') { // 点击的是小状态下的置忙

                    var statusText = $(this).attr('data-statusCode');

                    phone.changeSmallStatus(statusText, function(res) {
                        console.log(res)
                        // 应该要去调置忙 接口
                        if (res.status === '0') {
                            $(that).siblings().show();
                            $(that).hide();
                            $('.phonebarstate').find('p').text(targetTxt);
                            curNotReadyTxt = targetTxt;
                            if (curStatus === '置闲' || curStatus === '整理') {
                                phone.defineEvent('btn_notready');
                            }
                        }
                    }); // 事件切换

                }
                $(".pho-changeState-sub").hide();
            });
            /*
            * 挂断事件
            * 接听事件
             */
            $phonebar.on("click","li:nth-child(1).icon-guaduan.allowed",function() {
                console.log('点击挂断按钮---');
                phone.defineEvent('btn_disconnect');
                $('.pho-input').val('');
                // $(this).css('cursor','not-allowed');
                $(this).removeClass('allowed').addClass('not-allowed');
            }).on("click","li:nth-child(1)>img",function() {
                console.log('点击接听按钮---');
                phone.defineEvent('btn_answer');
            });
            /*
            * 保持事件
            * 接回事件
             */
            $phonebar.on("click",".pho-state-change.calling>.font1",function(e) {
                e.stopPropagation();
                e.preventDefault();
                var text = $(this).html();
                if(text === "保持"){
                    phone.defineEvent('btn_holdon');
                }else if(text === "接回"){
                    phone.defineEvent('btn_callback');
                }
            })
            /*
            显示咨询面板
             */
            function doGetAgent(showType) {
                phone.ucObj.doGetAgent(showType,function(data){
                    console.log(data)
                    if(data.Code == "0") {
                        // 模拟数据
                        // data.Msg = 'lihy:座席列表;:李泓莹::sip:30004';
                        var tree = msg2Tree(data.Msg);//将服务器收到的msg转为树形结构对象
                        console.log('tree-----', tree)
                        //var tree = msg2Tree('30006:业务咨询;:胡静::24|');//将服务器收到的msg转为树形结构对象
                        var html = tree2html(tree);//将树形结构对象生成ul下的多个li html片段
                        var $li_first = $(".searchStaff");
                        $li_first.siblings().remove();//先删除第一个li的所有兄弟
                        $li_first.after(html);//再在第一个li后追加tree2html()生成的HTML代码片段
                    }
                });
            }
            function zixunListShowInit() {
                $('.pho-group-line').show();
                $('.pho-group').css('height', '194px');
                if($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
                    // 当前选中的是外线
                    $('.pho-chioces2').show();
                } else {
                    $('.pho-chioces1').show();
                }
                
            }


            $phonebar.on("click",".pho-state-change.calling>.font2",function(e){
                e.stopPropagation();
                e.preventDefault();
                $('.pho-group-confirm').show();
                $('.pho-group-confirm-meet').hide();
                $('.pho-group-confirm-tran').hide();
                $('.pho-group-outerline').show();
                var text = $(this).html();
                if(text === "咨询"){
                    $zixunList.toggle();
                    var display = $zixunList.css('display');
                    if (display === 'block') {
                        showListType = 0;
                        showType = 0;
                        zixunListShowInit();  // 咨询面板内线外线都显示
                        $advisoryHead.html('咨询<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>')
                        doGetAgent(showType);

                        $('.pho-chongzhi-li>.pho-chongzhi,.pho-changeState>.pho-changeState-sub,.pho-panel>.pho-bohaopan').hide();
                    }
                }else if(text === "接回"){
                    phone.defineEvent('btn_reconnectCall');
                }

            })
            /*
            *转接事件
             */
            $phonebar.on("click",".pho-state-change.calling>.font3",function(e){
                e.stopPropagation();
                e.preventDefault();
                phone.defineEvent('btn_transfer');
            })
            /*
            *会议事件
             */
            $phonebar.on("click",".pho-state-change.calling>.font4",function(e){
                e.stopPropagation();
                e.preventDefault();
                phone.defineEvent('btn_meet');
                $('.pho-chongzhi-li>.pho-chongzhi,.pho-changeState>.pho-changeState-sub,.pho-panel>.pho-bohaopan').hide();
            })


            /*
             *咨询监听事件
             */
            $zixunList.on("click",".pho-group-confirm",function(e){ //确定按钮
                e.preventDefault();
                if($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
                    // 外线的电话号码
                    targetNum = conferenceParty = $('.pho-chioces2>li>div>input').val();
                }else{
                    //分机号
                    targetNum = conferenceParty = $("[data-group=phon-group]").children().children('.on').siblings().children("[data-edn=endn]").html();
                }
                console.log('iooo-----', targetNum)
                //根据查询人员列表的参数判断是咨询还是监听
                if(showType === 0){ //0 咨询
                    //调用咨询接口
                    //phone.defineEvent('btn_consult')

                   var text =  $('.pho-state-change.calling>.font2').html();
                    if(text === "咨询"){
                        doConsult();
                    }
                    $zixunList.hide();
                }else{              //2 监听
                    //调用监听接口
                    conferenceParty = $("[data-group=phon-group]").children().children('.on').siblings().children("[data-eid=eid]").html();
                    destAgentID = conferenceParty;
                    phone.defineEvent('btn_monitor',{'conferenceParty': conferenceParty})
                    $zixunList.hide();
                }

            })

            /*
             *单步 转接 会议
             */
            $phonebar.on("click",".pho-state-change.calling>.font11",function(e){
                e.stopPropagation();
                e.preventDefault();
                $('.pho-group-outerline').show();
                $('.pho-group-confirm').hide();
                $('.pho-group-confirm-meet').show();
                $('.pho-group-confirm-tran').show();
                $zixunList.toggle();
                var display = $zixunList.css('display');
                if (display === 'block') {
                    showType = 3;
                    $advisoryHead.html('单步<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>');
                    zixunListShowInit();  // 咨询面板内线外线都显示
                    doGetAgent(showType);
                }
            })
            /*
            *单步 转接事件
            */
            $zixunList.on("click",".pho-group-confirm-tran",function(e){ //确定按钮
                e.preventDefault();
                if($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
                    // 外线的电话号码
                    targetNum = conferenceParty = $('.pho-chioces2>li>div>input').val();
                }else{
                    //工号
                    targetNum = conferenceParty = $("[data-group=phon-group]").children().children('.on').siblings().children("[data-eid=eid]").html();
                }
                //根据查询人员列表的参数判断是咨询还是监听
                if(showType === 3){ //0 单步
                    //调用咨询接口
                    //phone.defineEvent('btn_consult')

                    var text =  $('.pho-state-change.calling>.font2').html();
                    doSingleStep(1)
                    $zixunList.hide();
                }

            })

                 /*
                 *单步 会议事件
                 */
            $zixunList.on("click",".pho-group-confirm-meet",function(e){ //确定按钮
                    e.preventDefault();
                    if($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
                        // 外线的电话号码
                        targetNum = conferenceParty = $('.pho-chioces2>li>div>input').val();
                    }else{
                        //工号
                        targetNum = conferenceParty = $("[data-group=phon-group]").children().children('.on').siblings().children("[data-eid=eid]").html();
                    }
                    //根据查询人员列表的参数判断是咨询还是监听
                    if(showType === 3){ //0 单步
                        //调用咨询接口
                        //phone.defineEvent('btn_consult')

                        var text =  $('.pho-state-change.calling>.font2').html();
                        doSingleStep(2)
                        $zixunList.hide();
                    }

            })



            /*
            *监听显示
             */
            $phonebar.on("click",".pho-state-change.calling>.font5",function(e){
                e.stopPropagation();
                e.preventDefault();
                $('.pho-group-confirm').show();
                $('.pho-group-confirm-meet').hide();
                $('.pho-group-confirm-tran').hide();
                $zixunList.toggle();
                var display = $zixunList.css('display');
                if (display === 'block') {
                    showType = 2;
                    $advisoryHead.html('监听<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>');
                    doGetAgent(showType);
                    // 咨询面板 只显示内线下方的框
                    $('.pho-group-line').hide();
                    $('.pho-group').css('height', '245px');
                    $('.pho-chioces2').hide();
                    $('.pho-chioces1').show();
                }
            })

            var destAgentID = '';

            /*
            *强拆事件
             */
            $phonebar.on("click",".pho-state-change.calling>.font6",function(e){
                e.stopPropagation();
                e.preventDefault();
                phone.defineEvent('btn_drop',{'destAgentID':destAgentID});
            })
            /*
            *强插事件
             */
            $phonebar.on("click",".pho-state-change.calling>.font7",function(e){
                e.stopPropagation();
                e.preventDefault();
                phone.defineEvent('btn_insert')
            })
            /*
            *转IVR
             */
            $phonebar.on("click",".pho-state-change.calling>.font8",function(e){
                e.stopPropagation();
                e.preventDefault();
                phone.defineEvent('btn_transferIvr')
            })

            /*
             *协作
             */
            $phonebar.on("click",".pho-state-change.calling>.font9",function(e){
                e.stopPropagation();
                e.preventDefault();
                phone.defineEvent('btn_cooperation')
            })
            /*
             *密语
             */
            $phonebar.on("click",".pho-state-change.calling>.font10",function(e){
                e.stopPropagation();
                e.preventDefault();
                var text = $(this).html();
                if(text === "密语") {
                    phone.defineEvent('btn_assistService',{'destType':1});
                }else if(text === "结束"){
                    phone.defineEvent('btn_assistService',{'destType':2})
                }
            })

            /*
            *拨号事件
            * 首先选择主叫号码---设置面板点击确认
             */
            $('.Determine').click(function(){
                if($('.automaticResponse .icon-weixuanzhongduoxuan').hasClass('on')){ //请用主叫号码
                    explicitNum =  $('.callingNumber').val();
                    phone.config.explicitNum = explicitNum;
                    if(explicitNum == ''){
                        alert('请选择外显号');
                        return;
                    }
                } else {
                    explicitNum = '';
                    phone.config.explicitNum = explicitNum;
                }
                $.cookie('explicitNum', explicitNum, { expires: 365 });
                //设置自动 置忙、置闲
                if($('.autoSetReadyResponse .icon-weixuanzhong').hasClass('on')){
                    autoReadyVal = $('.autoSetReadyResponse .on').attr("id");
                    acwTimerVal = $('#acwTimer').val();
                    if(acwTimerVal == ''){
                        alert('请输入事后整理时长');
                        return;
                    }else{
                        phone.config.autoReadyKey = autoReadyVal;
                        phone.config.acwTimerKey = acwTimerVal;
                        $.cookie('autoReadyKey', autoReadyVal, { expires: 365 });
                        $.cookie('acwTimerKey', acwTimerVal, { expires: 365 });
                    }
                }else{
                    $.removeCookie('autoReadyKey');
                    $.removeCookie('acwTimerKey');
                    phone.config.autoReadyKey = '';
                    phone.config.acwTimerKey = 0 ;
                }

                //设置坐席助手
                var setAIParam = {state: ''};
                var cookieAISet = $.cookie('autoAIHelpKey');
                console.log('-------智能助手的cookie-配置', cookieAISet);
                if($('.autoAIResponse .icon-weixuanzhongduoxuan').hasClass('on')){
                    autoAIHelpVal = 'autoAIHelp';
                    phone.config.autoAIHelpKey = autoAIHelpVal;
                    if (null==cookieAISet || cookieAISet==''|| typeof(cookieAISet)=='undefined') { // 智能助手未设置启动
                        setAIParam.state = 'ON';
                        setAgentHelperAuth(setAIParam, function(res) {
                            if (res.code != 200) {
                                console.log('智能助手启动失败--');
                                $('.autoAIResponse .icon-weixuanzhongduoxuan').removeClass("on");
                                autoAIHelpVal = '';
                                phone.config.autoAIHelpKey = autoAIHelpVal;
                                $.cookie('autoAIHelpKey', autoAIHelpVal, { expires: 365 });
                            }
                        });
                    }
                } else {
                    autoAIHelpVal = '';
                    phone.config.autoAIHelpKey = autoAIHelpVal;
                    if (null!=cookieAISet && cookieAISet!=''&& typeof(cookieAISet)!='undefined') { // 智能助手设置启动了，需要关闭
                        setAIParam.state = 'OFF';
                        setAgentHelperAuth(setAIParam, function(res) {
                            if (res.code != 200) {
                                console.log('智能助手关闭失败--');
                                $('.autoAIResponse .icon-weixuanzhongduoxuan').addClass("on");
                                autoAIHelpVal = 'autoAIHelp';
                                phone.config.autoAIHelpKey = autoAIHelpVal;
                                $.cookie('autoAIHelpKey', autoAIHelpVal, { expires: 365 });
                            }
                        });
                    }
                }

                $.cookie('autoAIHelpKey', autoAIHelpVal, { expires: 365 });
                 
                // 设置呼入自动应答
                if($('.autoSetAnswer .icon-weixuanzhongduoxuan').hasClass('on')){
                    autoAnswerCallInVal = 'autoAnswerCallIn';
                    phone.config.autoAnswerCallInKey = autoAnswerCallInVal;
                } else {
                    autoAnswerCallInVal = '';
                    phone.config.autoAnswerCallInKey = autoAnswerCallInVal;
                }
                $.cookie('autoAnswerCallInKey', autoAnswerCallInVal, { expires: 365 });

                $callSetting.hide();

            })
            $(".phonebar>li:nth-child(4)").phopanel("panel1",phone,explicitNum);
            $(".pho-chioces2>li").phopanel("panel2",phone,explicitNum);
            /*
            *关闭咨询面板事件
             */
            $phonebar.on("click",".pho-advisory .icon-guanbi",function(e){
                e.stopPropagation();
                e.preventDefault();
                showListType = "";
                $zixunList.hide();
            })
            /*
            *设置及重置面板事件
            * 面板显隐
           */
            $phonebar.on("click",".pho-chongzhi-li",function(e){
                e.stopPropagation();
                e.preventDefault();
                $settingPanel.toggle();
            })
            /*
            *重置事件
           */
            $phonebar.on("click",".pho-chongzhi>.htn_reset",function(e){
                var msg = "注意!\n若您当前正在通话,重置后,当前通话将断开!\n是否仍要重置?"
                if(confirm(msg) == true) {
                    e.stopPropagation();
                    e.preventDefault();
                    $settingPanel.hide();
                    phone.defineEvent('btn_reset')
                }

            })
            /*
            *按钮隐藏事件
           */
            $phonebar.on("click",".pho-chongzhi>.btn_transferIvr,.pho-chongzhi>.btn_monitor,.pho-chongzhi>.btn_insert,.pho-chongzhi>.btn_drop,.pho-chongzhi>.btn_cooperation,.pho-chongzhi>.btn_assistService",function(e){
                e.stopPropagation();
                e.preventDefault();
                var btnClass = $(this).attr('class');
                var  btnxuanzhong = $('.pho-chongzhi> .'+btnClass).children('.icon-weixuanzhongduoxuan');
                if($(btnxuanzhong).hasClass("on")){
                    $(btnxuanzhong).removeClass("on")
                    $('.pho-state-change.'+btnClass).hide();
                    $phonebar.width($phonebar.width() - 45);
                }else{
                    $(btnxuanzhong).addClass("on");
                    $('.pho-state-change.'+btnClass).show();
                    $phonebar.width($phonebar.width() + 45);
                }

            })

            /*
            *咨询面板事件
           */
            //一级菜单显示隐藏
            $(".pho-chioces1").on("click", ".pho-group ul>li:not(.searchStaff)", function (e) {
                e.stopPropagation();
                var $li = $(this);
                if ($li.children().first().is(".rotateZ9")) {//现在是收起
                    //就展开
                    $li.children().first().removeClass('rotateZ9')
                        .next('.icon-weixuanzhong').addClass("on")//开灯
                        .next().next().show();
                    //兄弟中的子元素都收起
                    $li.siblings(":not(.searchStaff)").children().first('.icon-xiajiantou').addClass('rotateZ9')
                        .next('.icon-weixuanzhong').removeClass("on")//关灯
                        .next().next().hide();
                } else {//如果现在是展开
                    //就只关闭自己，不管别人
                    $li.children().first().addClass('rotateZ9')
                        .next('.icon-weixuanzhong').removeClass("on")
                        .next().next().hide();
                }
            })
            //二级菜单显示隐藏
                .on("click", "[data-group=phon-group]>li", function (e) {
                    e.stopPropagation();
                    var $li = $(this);
                    if (!$li.children().first().is(".on")) {//只有灭时
                        $li.children().first().addClass("on");
                        $li.siblings().children("span:nth-child(1)").removeClass("on");
                    }else{
                        $li.children().first().removeClass("on");
                    }
                })
            /*
             *咨询执行
             */
            function doConsult() {
                if($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')){
                    var consultType = 2;
                    showType = 0;
                    if(targetNum.indexOf('sip:') === -1) {
                        targetNum = "Tel:" + targetNum;
                    }
                    phone.defineEvent('btn_consult',{'consultType': consultType,'targetNum': targetNum});
                    console.log('执行了外线咨询')
                }else{
                    console.log('i000----', targetNum)
                    var consultType = 1;
                    showType = 0;
                    if(targetNum.indexOf('sip:') === -1) {
                        targetNum = "sip:" + targetNum;
                    }
                    console.log('执行了内线咨询')
                    phone.defineEvent('btn_consult',{'consultType': consultType,'targetNum': targetNum});
                }
            }

            /**
             *  单步执行
             * @param destId
             */
            function doSingleStep(destId) {
                        if($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')){
                            var consultType = 2;
                            showType = 3;
                            if(targetNum.indexOf('sip:') === -1) {
                                targetNum = "Tel:" + targetNum;
                            }
                            phone.defineEvent('btn_singleStep',{'consultTypeId': consultType,'destId':destId,'targetNumber': targetNum});
                            console.log('执行了外线咨询')
                        }else{
                            var consultType = 1;
                            showType = 3;
                            if(targetNum.indexOf('sip:') === -1) {
                                targetNum = "sip:" + targetNum;
                            }
                            console.log('执行了内线咨询')
                            phone.defineEvent('btn_singleStep',{'consultTypeId': consultType,'destId':destId,'targetNumber': targetNum});
                        }
                    }

/*            /!*
             *切换内外线事件
             *!/
            $(".pho-group-line>span:first-child").click(function () {
                $(this).children().first().addClass("on").parent().next().children().first().removeClass("on");
                $(".pho-chioces1").show().next().hide();
            })
            $(".pho-group-line>span:last-child").click(function () {
                $(this).children().first().addClass("on").parent().prev().children().first().removeClass("on");
                $(".pho-chioces2").show().prev().hide();
            })*/

            /*
             *切换内外线事件
             */
            //显示座席
            $("#zixunList .pho-group-line>.pho-group-line-btn:nth-child(1)").click(function () {

                $(this).siblings().children().removeClass('on');  // 删除其他兄弟元素的样式
                $(this).children().first().addClass("on");  // 删除其他兄弟元素的样式
                $("#zixunList .pho-chioces1").show();

                $("#zixunList .pho-chioces1").siblings("ul").hide();
            })

            //显示内线
            $("#zixunList .pho-group-line>.pho-group-line-btn:nth-child(2)").click(function () {
                $(this).siblings().children().removeClass('on');  // 删除其他兄弟元素的样式
                $(this).children().first().addClass("on");  // 删除其他兄弟元素的样式
                $("#zixunList .pho-chioces2").show();

                $("#zixunList .pho-chioces2").siblings("ul").hide();
            })

            /*
             *滚动
             */
            $('.scrollbar-inner').scrollbar();

            /*
            *设置面板
            */
            // 设置面板显示
            $phonebar.on("click", ".setOnCall", function () {
                phone.ucObj.doGetShowANI(function(data) {
                    console.log("++++++++----"+data)
                    if (data.Code === '0') {
                        //将外显号码曝出
                       explicitNumRender(data['Msg']);

                    }
                })
                var explicitNumKey = $.cookie('explicitNum');
                if(explicitNumKey !='' && typeof(explicitNumKey) !='undefined' && explicitNumKey !=null){

                    $('.automaticResponse .icon-weixuanzhongduoxuan').addClass("on");
                    $callingNumber.css("cursor","pointer");
                    $callingNumber.val(explicitNumKey);
                }else{
                    $('.automaticResponse .icon-weixuanzhongduoxuan').removeClass("on");
                    $callingNumber.css("cursor","not-allowed");
                    $callingNumber.val('');
                    $callingNumberList.hide();
                }

                $('#acwTimer').val($.cookie('acwTimerKey'));
                var autoReadyKey = $.cookie('autoReadyKey');
                $('.autoSetReadyResponse').find("#"+autoReadyKey).addClass("on");
                $('.autoSetReadyResponse').find("#"+autoReadyKey).siblings().removeClass("on");
                
                // 设置中的智能助手
                var autoAIHelpKey  = $.cookie('autoAIHelpKey');
                console.log('点开设置面板的-获取到的智能助手设置--', autoAIHelpKey);
                if(autoAIHelpKey !='' && typeof(autoAIHelpKey) !='undefined' && autoAIHelpKey !=null){
                    $('.autoAIResponse .icon-weixuanzhongduoxuan').addClass("on");
                }else{
                    $('.autoAIResponse .icon-weixuanzhongduoxuan').removeClass("on");
                }

                // 设置中的呼入自动接听
                var autoAnswerCallInKeyGet  = $.cookie('autoAnswerCallInKey');
                if(null!=autoAnswerCallInKeyGet && autoAnswerCallInKeyGet!=''&& typeof(autoAnswerCallInKeyGet)!='undefined'){
                    $('.autoSetAnswer .icon-weixuanzhongduoxuan').addClass("on");
                }else{
                    $('.autoSetAnswer .icon-weixuanzhongduoxuan').removeClass("on");
                }

                $callSetting.show();
            })
            // 设置面板关闭
            $('.setUpTitle .icon-guanbi').click(function(){
                $callingNumberList.hide();
                $settingPanel.hide();
                $callSetting.hide();
            })
            // 设置面板取消
            $('.Unset').click(function(){
                $callingNumberList.hide();
                $callSetting.hide();
                $settingPanel.hide();
            })

            $('.automaticResponse').on("click",".icon-weixuanzhongduoxuan",function(){
                if($(this).hasClass("on")){
                    $(this).removeClass("on");
                    $callingNumber.css("cursor","not-allowed");
                    $callingNumber.val('');
                    $callingNumberList.hide();
                } else {
                    $(this).addClass("on");
                    $callingNumber.css("cursor","pointer")
                }
            })
            // 主叫 （外显号码列表）显隐
            $callingNumber.click(function(){
                if($('.automaticResponse .icon-weixuanzhongduoxuan').hasClass("on")){
                    $callingNumberList.toggle();
                } else {
                    $callingNumberList.hide();
                }
            });
            // 主叫 （外显号码列表）选择
            $callingNumberList.on("click","li",function(){
                $callingNumber.val($(this).text());
                $callingNumberList.hide();
            })
            // 自动设置置闲 置忙
            $('.autoSetReadyResponse').on("click",".icon-weixuanzhong",function(){
                if($(this).hasClass("on")){
                    $(this).removeClass("on");
                    $(this).siblings().removeClass("on");
                } else {
                    $(this).addClass("on");
                    $(this).siblings().removeClass("on");
                }

            })
             // 是否启动AI坐席助手
            $('.autoAIResponse').on("click",".icon-weixuanzhongduoxuan",function(){
                if($(this).hasClass("on")){
                    $(this).removeClass("on");
                } else {
                    $(this).addClass("on");
                }
            })
            // 自动呼入应答
            $('.autoSetAnswer').on("click",".icon-weixuanzhongduoxuan",function(){
                if($(this).hasClass("on")){
                    $(this).removeClass("on");
                } else {
                    $(this).addClass("on");
                }
            })
            // 电话条提示面板关闭
            $unknownTip.on('click', 'i', function() {
                $unknownTip.hide(500);
                $unknownTip.removeClass('sipmlError');
            })

            // 本地声音播放结束事件
            var localAudio = document.getElementById('audio_local');
            localAudio.addEventListener('ended', function() {
                console.log('播放结束播放结束----');
                var local_audio_src = '';
                localAudio.src = local_audio_src;
                localAudio.pause();
            })
        })






